import * as fflate from 'fflate'
import bcrypt from 'bcryptjs'

const CLIENT_SALT = '$2a$10$bNVbgiLkyewJT8IOaQY0Zu'

export async function passwordClientBcrypt (password: string): Promise<string> {
  const hash = await bcrypt.hash(password, CLIENT_SALT)
  return hash.toString()
}

export function compressStrToBase64 (utf8Str: string) {
  const buf = fflate.strToU8(utf8Str)
  const compressedUint8 = fflate.compressSync(buf, {
    level: 6,
    mem: 8
  })
  return Buffer.from(compressedUint8).toString('base64')
}

export function decompressBase64ToStr (base64Str: string) {
  const compressed = Buffer.from(base64Str, 'base64')
  const decompressed = fflate.decompressSync(compressed)
  return fflate.strFromU8(decompressed)
}

/**
 * 存储对象
 * @param key
 * @param data
 */
export function saveObject (key: string, data: object) {
  const dataStr = JSON.stringify(data)
  const dataBase64 = compressStrToBase64(dataStr)
  return localStorage.setItem(key, dataBase64)
}

/**
 * 读取对象
 * @param key
 */
export function loadObject (key: string) {
  // [?] 'null' 不是合法的 base64
  const dataBase64 = localStorage.getItem(key) || ''
  const dataStr = decompressBase64ToStr(dataBase64)
  if (dataStr) {
    return JSON.parse(dataStr)
  }
  return
}
